package com.example.moshudriver.fragment;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.BeeFramework.model.BusinessResponse;
import com.BeeFramework.view.MyDialog;
import com.BeeFramework.view.ToastView;
import com.example.moshudriver.HelpActivity;
import com.sgr.dykdriver.R;
import com.example.moshudriver.activity.AboutMoShu;
import com.example.moshudriver.activity.B0_SigninActivity;
import com.example.moshudriver.activity.C13_EditPasswordActivity;
import com.example.moshudriver.activity.C16_FeedbackActivity;
import com.example.moshudriver.activity.SlidingActivity;
import com.example.moshudriver.model.UserBalanceModel;
import com.example.moshudriver.protocol.ApiInterface;
import com.example.moshudriver.protocol.USER;
import com.example.moshudriver.tools.MessageConstant;
import com.example.moshudriver.tools.O2OMobileAppConst;
import com.example.moshudriver.tools.SESSION;
import com.example.moshudriver.tools.StreamTools;
import com.external.androidquery.callback.AjaxStatus;
import com.external.eventbus.EventBus;

public class SettingFragment extends Fragment implements OnClickListener,
		BusinessResponse {

	private TextView mTitle;
	SharedPreferences mShared;
	Editor mEditor;
	private USER mUser;
	private RelativeLayout mChangePassword;
	private RelativeLayout mAbout;
	private RelativeLayout mFeedBack;
	private RelativeLayout mUpdate;
	// private RelativeLayout mVoice_switch;
	private UserBalanceModel mUserBalance;
	private Button mLogout;
	private String description;
	private String apkurl;
	protected static final int SHOW_UPDATE_DIALOG = 0;
	protected static final int URL_ERROR = 1;
	protected static final int NETWORK_ERROR = 2;
	protected static final int JSON_ERROR = 3;
	private NotificationManager mNotificationManager;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mShared = getActivity().getSharedPreferences(
				O2OMobileAppConst.USERINFO, 0);
		mEditor = mShared.edit();
		View view = inflater.inflate(R.layout.f9_setting, null);
		view.setOnClickListener(null);
		mTitle = (TextView) view.findViewById(R.id.top_view_title);
		mTitle.setText(getString(R.string.setting));
		mLogout = (Button) view.findViewById(R.id.btn_logout);
		mBack = (ImageView) view.findViewById(R.id.top_view_back);
		String userStr = mShared.getString("user", "");
		try {
			if (userStr != null) {
				JSONObject userJson = new JSONObject(userStr);
				mUser = new USER();
				mUser.fromJson(userJson);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mChangePassword = (RelativeLayout) view
				.findViewById(R.id.change_password);
		mAbout = (RelativeLayout) view.findViewById(R.id.about);
		mFeedBack = (RelativeLayout) view.findViewById(R.id.feedback);
		mUpdate = (RelativeLayout) view.findViewById(R.id.update);
		mHelper = (RelativeLayout) view.findViewById(R.id.software_helper);

		mUpdate.setOnClickListener(this);
		mHelper.setOnClickListener(this);
		// mVoice_switch.setOnClickListener(this);
		mFeedBack.setOnClickListener(this);
		mAbout.setOnClickListener(this);
		mChangePassword.setOnClickListener(this);
		mLogout.setOnClickListener(this);

		mUserBalance = new UserBalanceModel(getActivity());
		mUserBalance.addResponseListener(this);

		if (!EventBus.getDefault().isregister(this)) {
			EventBus.getDefault().register(this);
		}
		return view;

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mBack.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				((SlidingActivity) getActivity()).showLeft();
			}
		});
	}

	@Override
	public void onDestroyView() {
		if (EventBus.getDefault().isregister(this)) {
			EventBus.getDefault().unregister(this);
		}
		super.onDestroyView();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		// case R.id.voice_switch:
		// Toast.makeText(getActivity(), "voice_switch", Toast.LENGTH_SHORT)
		// .show();
		// break;
		case R.id.software_helper:
			Intent helpIntent = new Intent(getActivity(), HelpActivity.class);
			startActivity(helpIntent);
			break;

		case R.id.btn_logout:
			// Toast.makeText(getActivity(), "您点击了btn_logout", 0).show();
			final MyDialog myDialog = new MyDialog(getActivity(), "是否注销该账户");
			myDialog.show();
			myDialog.positive.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					mUserBalance.signout();
					myDialog.dismiss();
				}
			});
			myDialog.negative.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					myDialog.dismiss();
				}
			});
			break;
		case R.id.change_password:
			// Toast.makeText(getActivity(), "您点击了change_password", 0).show();
			intent = new Intent(getActivity(), C13_EditPasswordActivity.class);
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			break;
		case R.id.about:
			// Toast.makeText(getActivity(), "您点击了about", 0).show();
			intent = new Intent(getActivity(), AboutMoShu.class);
			// intent.putExtra(WebViewActivity.WEBURL,
			// "http://www.o2omobile.com.cn");
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			break;
		case R.id.feedback:
			// Toast.makeText(getActivity(), "您点击了feedback", 0).show();
			intent = new Intent(getActivity(), C16_FeedbackActivity.class);
			startActivity(intent);
			getActivity().overridePendingTransition(R.anim.push_right_in,
					R.anim.push_right_out);
			break;
		case R.id.update:
			// Toast.makeText(getApplicationContext(), "您点击了更新", 0).show();
			// 检查更新
			checkUpdate();
			break;
		}

	}

	private void checkUpdate() {
		new Thread() {

			public void run() {

				Message msg = Message.obtain();
				try {
					URL url = new URL(ApiInterface.UPDATE_URL);
					// 联网
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					// 请求方式
					conn.setRequestMethod("GET");
					// 请求超时时间
					conn.setConnectTimeout(4000);
					// 获取请求返回码
					int code = conn.getResponseCode();
					if (code == 200) {// 联网成功
						InputStream inputStream = conn.getInputStream();
						// 把流转化为string
						String result = StreamTools.readFromStream(inputStream);
						Log.i("联网情况：", "联网成功了" + result);
						// json解析
						JSONObject obj = new JSONObject(result);
						// 从服务器获取到版本信息
						String version = (String) obj.get("version");
						// String version = obj.getString("version");
						Log.i("version", version);
						// 版本描述
						description = (String) obj.get("description");
						Log.i("version", description);
						// apk的url
						apkurl = (String) obj.get("moshudriverapkurl");
						Log.i("version", apkurl);

						// 判断当前版本和服务器的是否匹配
						if (getVersionName().equals(version)) {
							Looper.prepare();
							// 版本一致，不需要进行更新
							Toast.makeText(getActivity(), "没有新版本,不需要更新", 0)
									.show();
							Looper.loop();
						} else {
							// 进行版本更新
							msg.what = SHOW_UPDATE_DIALOG;
						}
					}

				} catch (MalformedURLException e) {
					msg.what = URL_ERROR;
					e.printStackTrace();
				} catch (IOException e) {
					msg.what = NETWORK_ERROR;
					e.printStackTrace();
				} catch (JSONException e) {
					msg.what = JSON_ERROR;
					e.printStackTrace();
				} finally {
					handler.sendMessage(msg);
				}
			}

		}.start();

	}

	private Handler handler = new Handler() {
		// 处理消息
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case URL_ERROR:// URL错误
				if (getActivity() != null) {
					Toast.makeText(getActivity(), "URL错误", 1000).show();
				}
				break;
			case NETWORK_ERROR:// 网络异常
				if (getActivity() != null) {
					Toast.makeText(getActivity(), "网络异常", 1000).show();
				}
				break;
			case JSON_ERROR:// JSON解析出错
				if (getActivity() != null) {
					Toast.makeText(getActivity(), "JSON解析出错", 1000).show();
				}
				break;
			// 获取到新版本，显示升级的对话框
			case SHOW_UPDATE_DIALOG:
				showUpdateDialog();
				break;

			default:
				break;
			}
		}
	};
	private ImageView mBack;
	private RelativeLayout mHelper;

	// 得到版本信息
	private String getVersionName() {
		// 用来管理手机的APK
		PackageManager pManager = getActivity().getPackageManager();
		try {
			// 得到知道APK的功能清单文件
			PackageInfo info = pManager.getPackageInfo(getActivity()
					.getPackageName(), 0);
			return info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		}
	};

	// 显示升级对话框
	private void showUpdateDialog() {
		// TODO Auto-generated method stub

		final MyDialog dialog = new MyDialog(getActivity(), description);
		dialog.positive.setText("立刻升级");
		dialog.positive.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dowmLoadAndInstall();
				dialog.dismiss();
			}
		});
		dialog.negative.setText("下次再说");
		dialog.negative.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		dialog.show();
		Log.i("升级信息", "进行升级");

		// AlertDialog.Builder builder = new Builder(getActivity());
		// builder.setTitle("提示升级");
		// builder.setOnCancelListener(new OnCancelListener() {
		//
		// @Override
		// public void onCancel(DialogInterface dialog) {
		// dialog.dismiss();
		// }
		// });
		// // 版本描述
		// builder.setMessage(description);
		// builder.setPositiveButton("立刻升级",
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dowmLoadAndInstall();
		//
		// }
		// });
		// builder.setNegativeButton("下次再说",
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// // TODO Auto-generated method stub
		// dialog.dismiss();
		// }
		// });
		// builder.create();
		// builder.show();
	}

	protected void dowmLoadAndInstall() {
		// 下载APK，并且替换安装
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// sdcard存在
			// afnal
			FinalHttp finalhttp = new FinalHttp();
			finalhttp.download(apkurl, Environment
					.getExternalStorageDirectory().getAbsolutePath()
					+ "/MoShuDriver2.0.apk", new AjaxCallBack<File>() {

				@Override
				public void onFailure(Throwable t, int errorNo, String strMsg) {
					t.printStackTrace();
					Toast.makeText(getActivity(), "下载失败", 1).show();
					super.onFailure(t, errorNo, strMsg);
				}

				// 通知栏显示下载进度
				@Override
				public void onLoading(long count, long current) {
					// TODO Auto-generated method stub
					super.onLoading(count, current);

					mNotificationManager = (NotificationManager) getActivity()
							.getSystemService(
									getActivity().NOTIFICATION_SERVICE);
					// 当前下载百分比
					int progress = (int) (current * 100 / count);
					NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
							getActivity());
					mBuilder.setContentTitle("正在下载")
							.setContentText(progress + "%")
							.setSmallIcon(R.drawable.logo).setAutoCancel(true)
							.setPriority(NotificationCompat.PRIORITY_MAX)
							.setTicker("正在下载最新版本");
					mNotificationManager.notify(0, mBuilder.build());
				}

				@Override
				public void onSuccess(File t) {
					// TODO Auto-generated method stub
					super.onSuccess(t);
					installAPK(t);
				}

				/**
				 * 安装APK
				 * 
				 * @param t
				 */
				private void installAPK(File t) {
					Intent intent = new Intent();
					intent.setAction("android.intent.action.VIEW");
					intent.addCategory("android.intent.category.DEFAULT");
					intent.setDataAndType(Uri.fromFile(t),
							"application/vnd.android.package-archive");
					startActivity(intent);
				}
			});
		} else {
			Toast.makeText(getActivity(), "没有sdcard，请安装上再试", 0).show();
			return;
		}

	}

	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		// TODO Auto-generated method stub
		if (url.endsWith(ApiInterface.USER_SIGNOUT)) {
			mEditor.putBoolean("isLogin", false);
			mEditor.putString("user", "");
			mEditor.putInt("uid", 0);
			mEditor.putString("sid", "");
			mEditor.commit();
			SESSION.getInstance().uid = mShared.getInt("uid", 0);
			SESSION.getInstance().sid = mShared.getString("sid", "");
			ToastView toast = new ToastView(getActivity(),
					getString(R.string.logout_success));
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			Message msg = new Message();
			msg.what = MessageConstant.LOGINOUT;
			EventBus.getDefault().post(msg);
			Intent intent = new Intent(getActivity(), B0_SigninActivity.class);
			startActivity(intent);
			// finish();//注意关闭
		}
	}

	public void onEvent(Object event) {
		Message message = (Message) event;
		if (message.what == MessageConstant.SETTING) {

		}
	}
}
